package com.glory.brepda.activity.mfg;

import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.brepda.R;
import com.glory.brepda.adapter.BinInfoListAdapter;
import com.glory.brepda.adapter.DataBinListAdapter;
import com.glory.brepda.base.BaseActivity;
import com.glory.brepda.callback.CustomDialogEntityCallBack;
import com.glory.brepda.entity.AvailableProgramBean;
import com.glory.brepda.entity.BinInfoEntity;
import com.glory.brepda.entity.LotInfoEntity;
import com.glory.brepda.entity.response.BaseResponseBean;
import com.glory.brepda.utils.LotUtils;
import com.glory.brepda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_CommonCallback;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_LogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_ToastUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * FileName: FTDataReportActivity
 * Author: XJH
 * Date: 2020/5/21 17:08
 * Description:数据上报（FT测试）
 * History:
 */
public class FTDataReportActivity extends BaseActivity {

    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.etEqpWork)
    FreeUI_ClearEditText etEqpWork;
    @BindView(R.id.etLot)
    FreeUI_ClearEditText etLot;
    @BindView(R.id.rvDataBinList)
    RecyclerView rvDataBinList;
    @BindView(R.id.tvGetData)
    LinearLayout tvGetData;
    @BindView(R.id.list_tv1)
    TextView listTv1;
    @BindView(R.id.list_tv2)
    TextView listTv2;
    @BindView(R.id.list_tv3)
    TextView listTv3;
    @BindView(R.id.list_tv4)
    TextView listTv4;
    @BindView(R.id.tvCustomerCode)
    TextView tvCustomerCode;
    @BindView(R.id.tvPartrrn)
    TextView tvPartrrn;
    @BindView(R.id.rvBINInfoList)
    RecyclerView rvBINInfoList;
    @BindView(R.id.tvPackageType)
    TextView tvPackageType;
    @BindView(R.id.tvMaterialType)
    TextView tvMaterialType;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.tvLotType)
    TextView tvLotType;
    @BindView(R.id.tvPartName)
    TextView tvPartName;
    @BindView(R.id.tvTestType)
    TextView tvTestType;
    @BindView(R.id.tvTestblock)
    TextView tvTestblock;
    @BindView(R.id.etTestMachine)
    FreeUI_ClearEditText etTestMachine;
    @BindView(R.id.flStationIDList)
    FrameLayout flStationIDList;
    @BindView(R.id.tvStationID)
    TextView tvStationID;
    @BindView(R.id.ivStationIDArrow)
    ImageView ivStationIDArrow;
    @BindView(R.id.checkbox)
    CheckBox checkbox;
    @BindView(R.id.llCheck)
    LinearLayout llCheck;
    private LotInfoEntity lotInfoEntity;
    private DataBinListAdapter mDataBinListAdapter;
    private BinInfoListAdapter mBinInfoListAdapter;
    private String mTestEqp = "";
    private List<BinInfoEntity.BinInfo> hbinData2;

    private ArrayList<String> stationidList = new ArrayList<>();
    private FreeUI_GeneralPop mStationIDPop;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_data_report;
    }

    @Override
    protected void initView() {
        initLayout();

        stationidList.add("A");
        stationidList.add("B");
        stationidList.add("C");
        stationidList.add("D");
        stationidList.add("ALL");

        initEdit(etLot, s -> LotUtils.searchLotInfo(FTDataReportActivity.this, s, getSupportFragmentManager(), new LotUtils.netCallback<LotInfoEntity>() {
            @Override
            public void onSuccess(LotInfoEntity response) {
                tvLotType.setText(response.getPART().getSPEC2());
                tvPartName.setText(response.getLOT().getPARTNAME());
                tvCustomerCode.setText(response.getLOT().getCUSTOMERCODE());
                tvPartrrn.setText(response.getLOT().getCUSTOMERPARTID());
                tvPackageType.setText(response.getPACKAGETYPE());
                tvMaterialType.setText(response.getLOT().getMATERIALTYPE());
                lotInfoEntity = response;
            }

            @Override
            public void onFail(Throwable t) {
                loadError(t, "LOTQUERY");
            }
        }));

        initEdit(etEqpWork, s -> {
            //通过设备获取所有信息
            if (lotInfoEntity == null){
                showToast("请先扫描Lot信息",false);
                return;
            }
            requestBinForType(s);
        });
    }

    public void requestBinForType(String eqpID) {
        FreeUI_EntityCallBack<BaseResponseBean<BinInfoEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<BinInfoEntity>>
                (new TypeToken<BaseResponseBean<BinInfoEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<BinInfoEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {

                    String testblock = "";
                    switch (response.body().getResponse().getBody().getTESTBLOCK()){
                        case "0":
                            testblock = "不分档";
                            break;
                        case "1":
                            testblock = "A";
                            break;
                        case "2":
                            testblock = "B";
                            break;
                        case "3":
                            testblock = "C";
                            break;
                        case "4":
                            testblock = "D";
                            break;

                    }
//                    tvTestblock.setText(testblock);
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<BinInfoEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "BININFOREQUEST");

            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("ACTIONTYPE", "Report");
        map.addProperty("EQUIPMENTID", eqpID);
        map.addProperty("LOTID", getText(etLot));
        map.addProperty("TESTTYPE", "");
        NetUtils.requestPostNet("RTM.BININFOREQUEST", "BININFOREQUEST", FTDataReportActivity.this, map, callBack);
    }

    private void getLotInfo(String lotid) {
        LotUtils.searchLotInfo(this, lotid, getSupportFragmentManager(), new LotUtils.netCallback<LotInfoEntity>() {
            @Override
            public void onSuccess(LotInfoEntity response) {
                lotInfoEntity = response;
            }

            @Override
            public void onFail(Throwable t) {
                loadError(t,"LOTQUERY");
            }
        });
    }

    private void initLayout() {
        listTv1.setText("BIN名称");
        listTv2.setText("BIN描述");
        listTv3.setText("设备计数");
        listTv4.setText("测试数量");
        llCheck.setVisibility(View.VISIBLE);
        String title = getIntent().getStringExtra(FreeApi_StaticMembers.SHOW_PLUGIN_KEY);
        tvTitle.setText(title);
        setMainLayout(llMain);
        rvDataBinList.setLayoutManager(new GridLayoutManager(this, 2));
        rvDataBinList.setItemAnimator(new DefaultItemAnimator());
        mDataBinListAdapter = new DataBinListAdapter(null, false);
        mDataBinListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mDataBinListAdapter.isFirstOnly(true);
        rvDataBinList.setAdapter(mDataBinListAdapter);
        initRecyclerView(rvBINInfoList, this);
        mBinInfoListAdapter = new BinInfoListAdapter(null, false);
        mBinInfoListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mBinInfoListAdapter.isFirstOnly(true);
        rvBINInfoList.setAdapter(mBinInfoListAdapter);

    }

    @Override
    protected void initData() {

    }

    @OnClick({R.id.tvBaseSubmit, R.id.tvGetData, R.id.flStationIDList})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tvBaseSubmit:
//                if (actionControl("Submit05")) {
//                    return;
//                }
                if (getText(etEqpWork).equals("")) {
                    showToast("设备信息不能为空", false);
                    return;
                }
                if (mBinInfoListAdapter.getData().size() <= 0){
                    showToast("请先获取数据",false);
                    return;
                }
                if (lotInfoEntity == null){
                    showToast("请先获取数据",false);
                    return;
                }
                List<BinInfoEntity.BinInfo> data = mBinInfoListAdapter.getData();
//                int sum = 0 ;
//                for (BinInfoEntity.BinInfo info : data){
//                    sum += Integer.parseInt(info.getBINACTUAL().equals("") ? "0" : info.getBINACTUAL());
//                }

//                if (sum <= 0){
//                    showToast("实测总数量为0，无法提交",false);
//                    return;
//                }

                if (!data.containsAll(hbinData2)){
                    data.addAll(hbinData2);
                }
//                LotUtils.binReport(this, getSupportFragmentManager(), "Report", "",
//                        getText(etLot), getText(etEqpWork), lotInfoEntity, data,"","",mTestEqp,"","TESTREPORTSUBMIT","ONLINE",new AvailableProgramBean(),"");
                FreeApi_DialogUtils.getConfirmAndCancelDialog(this, "确定要提交?", new FreeUI_CommonCallback() {
                    @Override
                    public void onSuccess() {
                        //确定
                        FreeUI_EntityCallBack<BaseResponseBean<JSONObject>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<JSONObject>>
                                (new TypeToken<BaseResponseBean<JSONObject>>() {
                                }.getType(), getSupportFragmentManager(), this) {

                            @Override
                            public void onSuccess(Response<BaseResponseBean<JSONObject>> response) {
                                super.onSuccess(response);
                                if (response.body().isSuccess(FTDataReportActivity.this, false, getSupportFragmentManager())) {
                                    FreeApi_ToastUtils.showFreeToast("提交成功", FTDataReportActivity.this, true, 0);
                                    finish();
                                }
                            }

                            @Override
                            public void onError(Response<BaseResponseBean<JSONObject>> response) {
                                super.onError(response);
                                FreeApi_LogUtils.saveErrorMessages(response.getException(), "TESTREPORTSUBMIT");
                                FreeApi_ToastUtils.showFreeToast("连接服务器失败", FTDataReportActivity.this, false, 0);
                            }
                        };
                        String s = tvTestType.getText().toString();
                        JsonObject map = new JsonObject();
                        map.addProperty("ACTIONTYPE", "Report");
                        map.addProperty("TESTTYPE", s.length()>=3?s.substring(0, 2):"");
                        map.addProperty("LOTID", getText(etLot));
                        map.addProperty("PRODUCTMODEL", lotInfoEntity.getPRODUCTMODEL());
                        map.addProperty("WIRINGNO", lotInfoEntity.getWIRINGNO());
                        map.addProperty("SEALNO", lotInfoEntity.getSEALNO());
                        map.addProperty("CHIPNAME", lotInfoEntity.getCHIPNAME());
                        map.addProperty("WIRESPEC", lotInfoEntity.getWIRESPEC());
                        map.addProperty("LINEID", lotInfoEntity.getLINEID());
                        map.addProperty("EQUIPMENTID", getText(etEqpWork));
                        map.addProperty("CHIPLOT", lotInfoEntity.getCHIPID());
                        map.addProperty("LOTTYPE", lotInfoEntity.getLOT().getLOTTYPE());
                        map.addProperty("PACKAGETYPE", lotInfoEntity.getLOT().getMAINMATTYPE());
                        map.addProperty("CUSTOMERCODE", lotInfoEntity.getLOT().getCUSTOMERCODE());
                        map.addProperty("LOTCOUNT", lotInfoEntity.getLOT().getMAINQTY());
                        map.addProperty("GRADENO", tvTestblock.getText().toString());
                        map.addProperty("EQPTYPE", "");
                        map.addProperty("TESTERIDS", mTestEqp);
                        map.addProperty("StationID", tvStationID.getText().toString());
                        map.addProperty("TESTBLOCK", "");
                        map.addProperty("CHIPNAME", lotInfoEntity.getCHIPNAME());
                        map.addProperty("OBJECTRRN", lotInfoEntity.getLOT().getOBJECTRRN());
                        map.addProperty("TesterEqpID", getText(etTestMachine));
                        map.addProperty("DataStatus", checkbox.isChecked()?"1":"0");
                        map.addProperty("CONNECTIONSTATE", "ONLINE");
                        map.add("HBINLIST", new JsonParser().parse(new Gson().toJson(mBinInfoListAdapter.getData())).getAsJsonArray());
                        NetUtils.requestPostNet("TESTREPORTSUBMIT", "TESTREPORTSUBMIT", FTDataReportActivity.this, map, callBack);

                    }
                }, () -> {
                }).show(getSupportFragmentManager(), "SUBMIT_DIALOG");

                break;
            case R.id.tvGetData:
                if (getText(etEqpWork).equals("")) {
                    showToast("请先扫描设备信息", false);
                    return;
                }

                requestBinInfo();
                break;
            case R.id.flStationIDList:
                if (mStationIDPop != null) {
                    if (mStationIDPop.isShowing()) {
                        mStationIDPop.dismiss();
                    }
                } else {

                    mStationIDPop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flStationIDList.getWidth(), stationidList, ivStationIDArrow, (codeS, i) -> {
                        tvStationID.setText(codeS);
                    });
                }
                FreeApi_PopUtils.setArrowShow(ivStationIDArrow);
                mStationIDPop.showAsDropDown(flStationIDList, 0, 0);
                break;
        }

    }

    private void requestBinInfo() {

        if (getText(etTestMachine).equals("")){
            showToast("测试机编号不能为空",false);
            return;
        }

        if (tvStationID.getText().toString().equals("")){
            showToast("站点不能为空",false);
            return;
        }

        FreeUI_EntityCallBack<BaseResponseBean<BinInfoEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<BinInfoEntity>>
                (new TypeToken<BaseResponseBean<BinInfoEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<BinInfoEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    tvTestType.setText(response.body().getResponse().getBody().getTESTTYPE());
                    tvTestblock.setText(response.body().getResponse().getBody().getTESTBLOCK());
                    if (response.body().getResponse().getBody().getHBINLIST().size() <= 0) {
                        showConfirmDialog("暂无数据");
                        return;
                    }
                    List<BinInfoEntity.BinInfo> hbinData = new ArrayList<>();
                    hbinData2 = new ArrayList<>();
                    List<BinInfoEntity.BinInfo> hbinlist = response.body().getResponse().getBody().getHBINLIST();
                    for (BinInfoEntity.BinInfo data : hbinlist){
                        if (data.getBINNO().contains("BIN")){
                            hbinData.add(data);
                        }else {
                            hbinData2.add(data);
                        }
                    }
//                    BinInfoEntity.BinInfo binInfo9 = new BinInfoEntity.BinInfo("BIN9", "少数(虚拟BIN)");
//                    BinInfoEntity.BinInfo binInfo10 = new BinInfoEntity.BinInfo("BIN10", "报废(虚拟BIN)");
//                    BinInfoEntity.BinInfo binInfo11 = new BinInfoEntity.BinInfo("BIN11", "样品");
//                    BinInfoEntity.BinInfo binInfo12 = new BinInfoEntity.BinInfo("BIN12", "未测BIN");
//                    BinInfoEntity.BinInfo binInfo13 = new BinInfoEntity.BinInfo("BIN13", "掉料(虚拟BIN)");
//                    hbinData.add(binInfo9);
//                    hbinData.add(binInfo10);
//                    hbinData.add(binInfo11);
//                    hbinData.add(binInfo12);
//                    hbinData.add(binInfo13);
                    mBinInfoListAdapter.setNewData(hbinData);

                    String testblock = "";
                    switch (response.body().getResponse().getBody().getTESTBLOCK()){
                        case "0":
                            testblock = "不分档";
                            break;
                        case "1":
                            testblock = "A";
                            break;
                        case "2":
                            testblock = "B";
                            break;
                        case "3":
                            testblock = "C";
                            break;
                        case "4":
                            testblock = "D";
                            break;

                    }
                    tvTestblock.setText(testblock);
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<BinInfoEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "EAP.GETHBINREQUEST");
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("EQPID", getText(etEqpWork));
        map.addProperty("LOTID", getText(etLot));
        map.addProperty("CONNECTIONSTATE", "ONLINE");
        map.addProperty("TESTTYPE", tvTestType.getText().toString());
        map.addProperty("TesterEqpID", getText(etTestMachine));
        map.addProperty("StationID", tvStationID.getText().toString());
        NetUtils.requestPostNet("EAP.GETHBINREQUEST", "GETHBINREQUEST", FTDataReportActivity.this, map, callBack);

    }

}
